<template>
  <div class="dashboard-container">
    <div class="app-container">
      <head-tool>
        <div class="btns" slot="after">
          <el-button type="info" size="small" @click="exportHeadExcel"
            >复杂导出</el-button
          >
          <el-button type="success" size="small" @click="exportExcel"
            >导出</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="$router.push({ path: '/import', query: { type: 'emp' } })"
            >导入</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="el-icon-circle-plus-outline"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </div>
      </head-tool>

      <el-card>
        <el-table :data="tableData">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="staffPhoto" label="头像" width="120px">
            <template slot-scope="{ row }">
              <img
                style="width:60px; border-radius:50%;"
                v-imgerror="defaultImg"
                :src="row.staffPhoto"
                alt=""
                @click="showQrcode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
          <el-table-column prop="workNumber" label="工号"></el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="{ row }">
              {{ row.formOfEmployment | formatHireType }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门"></el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" width="120px">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="状态">
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="260px">
            <div
              slot-scope="{ row }"
              style="display:flex;justify-content:space-between"
            >
              <el-link
                type="success"
                @click="
                  $router.push({
                    path: '/employees/detail',
                    query: { id: row.id }
                  })
                "
                >查看</el-link
              >
              <el-link type="success">转正</el-link>
              <el-link type="success">调岗</el-link>
              <el-link type="success">离职</el-link>
              <el-link type="success" @click="showDia(row.id)">角色</el-link>
              <el-link @click="delEmp(row.id)" type="success">删除</el-link>
            </div>
          </el-table-column>
        </el-table>
        <el-pagination
          style="text-align:center;margin-top:20px"
          :current-page="pageInfo.page"
          :page-size="pageInfo.size"
          :total="pageInfo.total"
          @current-change="pageChange"
          layout="total, prev, pager, next"
        />
      </el-card>
      <addEmp :showDialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCode" width="30%">
        <el-row type="flex" justify="center">
          <canvas ref="canvas"></canvas>
        </el-row>
      </el-dialog>
      <role-setting :showRole.sync="cancelShow" :userId="currentId" ref="roleSet" />
    </div>
  </div>
</template>

<script>
import { getEmpList, delEmpList } from '@/api/employees'
import constant from '@/api/constant/employees'
import addEmp from './components/add-emp.vue'
// 处理日期的函数
import { formatDate } from '@/filters'
// 导入二维码的插件
import Qrcode from 'qrcode'
// 导入角色分类对话框
import roleSetting from './components/role-setting.vue'
export default {
  name: 'emp',
  components: { addEmp, roleSetting },
  data () {
    return {
      currentId: '',
      cancelShow: false,
      showDialog: false,
      showCode: false,
      defaultImg: require('../../assets/common/zhanwei.jpeg'),
      tableData: [],
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  created () {
    this.getEmpList()
  },
  methods: {
    async showDia (id) {
      this.currentId = id
      this.cancelShow = true
      await this.$refs.roleSet.getUserProfile(id)
    },
    showQrcode (url) {
      // 显示对话框
      if (url) {
        this.showCode = true
        this.$nextTick(() => {
          Qrcode.toCanvas(this.$refs.canvas, '666')
        })
      } else {
        this.$message.warning('该员工没有添加加图片!')
      }
    },
    async getEmpList () {
      let res = await getEmpList(this.pageInfo)
      this.tableData = res.data.rows
      this.tableData.forEach(item => {
        item.enableState = item.enableState == 1 ? true : false
      })
      this.pageInfo.total = res.data.total
    },
    async delEmp (id) {
      try {
        await this.$confirm('您确定要删除吗?')
        await delEmpList(id)
        this.$message.success('删除员工成功!')
        if (this.tableData.length == 1 && this.pageInfo.page != 1) {
          this.pageInfo.page--
        }
        this.getEmpList()
      } catch (error) {
        console.log(error)
      }
    },
    pageChange (page) {
      this.pageInfo.page = page
      this.getEmpList()
    },
    // 导出的事件
    async exportExcel () {
      // 请求所有的员工数据
      let res = await getEmpList({
        page: 1,
        size: this.pageInfo.total
      })
      let list = res.data.rows
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      let keys = Object.keys(headers)
      let bigArr = list.map(item => {
        let arr = []
        for (let key in headers) {
          let engKey = headers[key]
          if (key == '入职日期' || key == '转正日期') {
            let res = formatDate(item[engKey])
            arr.push(res)
          } else if (key == '聘用形式') {
            let str = item[engKey] == 1 ? '正式' : '未知'
            arr.push(str)
          } else {
            arr.push(item[engKey])
          }
        }
        return arr
      })
      // 懒加载使用插件的方法
      // 哪里要用就在那里导入插件对应的js
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: keys, //表头 必填
          data: bigArr, //具体数据 必填
          filename: '员工列表',
          bookType: 'xlsx'
        })
      })
    },
    exportHeadExcel () {
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: [
            '姓名',
            '手机号',
            '入职日期',
            '聘用形式',
            '转正日期',
            '工号',
            '部门'
          ], //表头 必填
          data: [['11', '22', '33', '44', '55', '66', '77']], //具体数据 必填
          filename: '复杂形式员工列表',
          bookType: 'xlsx',
          multiHeader: [['姓名', '猪八戒', '唐三藏', '沙和尚', '', '', '部门']],
          merges: ['A1:A2']
        })
      })
    }
  },
  filters: {
    formatHireType (val) {
      let list = constant.hireType.filter(item => item.id == val)
      return list[0] ? list[0].value : '未知'
    }
  }
}
</script>

<style></style>
